var express = require('express');
var router = express.Router();

//表现层,获取用户
const { getusers2,login2,register2} = require("../service/usersService")
router.get('/', async (req, res, next) => {
  res.send(await getusers2(req.query));
});


//登录
router.post('/login',async (req,res,next)=>{
  const data = await login2(req.body);
  if(data.length == 0){
    res.send(false);
  }else{
    req.session.loginphone = data[0].phone;
    req.session.login_id = data[0]._id;
    req.session.loginname = data[0].name;
    res.send(true);
  }
});
//注册
router.post('/register',async (req,res,next)=>{
  res.send(await  register2(req.body)) ;
});

//判断是否登录
router.get('/islogin', (req, res, next)=> {
  const {loginphone,login_id,loginname} = req.session;
  if (login_id) {
      res.send({islogin:true,loginphone,login_id,loginname});
  } else {
      res.send({
          islogin: false
      });
  }
})


//注销
router.get('/logout', function (req, res, next) {
  req.session.destroy(function(){
      res.clearCookie('currentUser');
      res.send(true);
  })
})


module.exports = router;
